package com.doit.day02;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;

public class ConsumerDemo2 {
    public static void main(String[] args) {
        Properties props = new Properties();
        //必须配置的参数
        props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"linux01:9092");
        props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.GROUP_ID_CONFIG,"reb");

        //选配的
        //是否自动创建topic 默认是true 自动创建
        props.setProperty("allow.auto.create.topics","true");
        //从哪里读取数据  earliest 最早的  latest 最新的
        props.setProperty("auto.offset.reset","earliest");
        //是否自动提交偏移量 提交到哪去 __consumer_offsets
        props.setProperty("enable.auto.commit","true");
        //自动提交偏移量的间隔时间
        props.setProperty("auto.commit.interval.ms","10000");

        props.setProperty(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,"org.apache.kafka.clients.consumer.CooperativeStickyAssignor");



        //先搞出来一个消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
        //在拉取数据之前，得告诉他，读取哪一个topic中的数据
        consumer.subscribe(Arrays.asList("reb-1", "reb-2"), new ConsumerRebalanceListener() {
            /**
             * 指的是回收之前，该消费者消费的分区是哪些
             * @param partitions
             */
            @Override
            public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
                System.out.println("回收之前消费的分区是："+partitions);

            }

            /**
             * 指的是重新分配完成之后，该消费者消费哪些分区的数据
             * @param partitions
             */
            @Override
            public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
                System.out.println("重新分配之后消费的分区是："+partitions);
            }
        });

        while (true){
            //获取数据
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(Long.MAX_VALUE));
        }
    }
}
